<template>
    <div class='goods'>
        <div class="container">
            <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" class="search-con">
                <el-row>
                    <el-form-item label="" prop="key" label-width="0px">
                        <el-input v-model="queryParams.key" placeholder="商品名称" clearable size="small" />
                    </el-form-item>
                    <el-form-item label="" prop="key_cate_name" label-width="0px">
                        <el-cascader style="width: 300px;" class="form-item-cascader" :key="resetCascader"
                                    ref="myCascader" v-model="cate_ids" placeholder="请选择分类" :options="cateList"
                                    :props="optionProps" @change="e => handleChange(e, cate_ids)"
                                    clearable></el-cascader>
                        <!-- <el-input v-model="queryParams.key_cate_name" placeholder="分类名称" clearable size="small" /> -->
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-row>
            </el-form>
            <el-row :gutter="10" class="mb8">
                <el-col :span="22">
                    <el-button type="primary" size="mini" @click="handleCreate()"
                        v-hasPermi="['product:manage:add']">批量下单</el-button>
                    <!-- curRow={};title = '新增商品';handleShow = 'add'; -->
                    <span style="margin-left: 25px; font-size:110%;font-weight: bold;color:#30B08F;">共{{ listCount
                    }}个</span>
                </el-col>
                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
            <el-table border v-loading="loading" :data="tableList" ref="tableList" v-tableHeight
                :height="tableList && tableList.length > 0 ? '900px' : '120px'" @selection-change="handleSelectionChange"
                @row-click="toggleSelection" :row-key="getRowKeys">
                <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
                <el-table-column label="商品名称" align="center" prop="name" />
                <el-table-column label="商品编号" align="center" prop="code" width="180" />
                <el-table-column label="商品图片" align="center" prop="cover">
                    <template slot-scope="scope">
                        <div v-if="scope.row.cover" class="img-list">
                            <el-image style="width: auto; height: 45px;" :src="scope.row.cover"
                                :preview-src-list="[scope.row.cover]">
                            </el-image>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="规格" align="center" prop="goods_spec" width="180">
                    <template slot-scope="scope">
                        <span>{{ scope.row.goods_spec.split(";;").toString().replace(/::/g, ':') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="销量" align="center" prop="number_virtual" />
                <el-table-column label="商品库存" align="center" prop="stock_total" />
                <el-table-column label="销售价格" align="center" prop="price_selling" />
                <el-table-column label="市场价格" align="center" prop="price_market" />
                <el-table-column label="购买数量">
                    <template slot="header" slot-scope="scope">
                        <div class="mgrinr1">购买数量</div>
                        <div style="color: red;">(下单必填，不填默认为1)</div>
                    </template>
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.stock_sales" placeholder=1 :placeholder-style="{ color: '#000000' }"
                            @keyup.native="scope.row.stock_sales = onInput(scope.row.stock_sales)" @click.native.stop>
                        </el-input>
                        <!-- <span v-else>{{ scope.row.stock_total }}</span> -->
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <!-- @click="title='详情';customerId=String(scope.row.id);handleShow='detail'" -->
                        <el-button v-if="statusShow" size="mini" type="text" icon="el-icon-document"
                            @click.native.stop="toDetail(scope.row)" v-hasPermi="['marketSales:admit:detail']">
                            查看详情
                        </el-button>
                        <el-button size="mini" type="text" @click.native.stop="handleCreate0(scope.row)"
                            v-hasPermi="['user:staff:stop']">下单
                        </el-button>

                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="pageCount > 0" :pageCount="pageCount" :page.sync="queryParams.page"
                :limit.sync="queryParams.limit" @pagination="getList" />

            <!-- 新增 -->
            <add v-if="handleShow == 'add' || handleShow == 'edit' || handleShow == 'detail'" :title="title"
                :handleShow="handleShow" :data="curRow" :submitShow="submitShow" @close="handleShow = ''" @load="getList" />
            <!-- :customerId="customerId" customerId=null; style="height: 300px;"-->
            <audit v-if="handleShow == 'audit'" :data="stockRow" @close="handleShow = ''" @load="getList" />

            <el-dialog title="选择发货地址" visible v-if="handleShow == 'assign'" @close="close()" width="85%" append-to-body
                :close-on-click-modal="false">
                <el-form ref="form" :model="form" :rules="rules" label-width="120px" v-loading="formLoading">
                    <el-form-item prop="staff_id" label="选择发货地址">
                        <el-select v-model="form.address_id" placeholder="请选择发货地址" clearable size="small" filterable
                            style="width: 650px;">
                            <el-option v-for="dict in addressList" :key="dict.id" :label="dict.detailed" :value="dict.id"
                                filterable>
                                <span>编号：{{ dict.id }}</span>
                                <span style="margin-left:20px;">收货人：{{ dict.name }}</span>
                                <span style="margin-left:20px; font-size: 13px">地址：{{ dict.province }}{{ dict.city }}{{
                                    dict.area }}{{ dict.detailed }}</span>
                                <span style="margin-left:20px; font-size: 13px">手机号：{{ dict.mobile }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="close()">取 消</el-button>
                    <el-button type="primary" @click="submit" :disabled="formLoading">确 定</el-button>
                </span>
            </el-dialog>

        </div>
    </div>
</template>
<script>
import throttle from 'lodash.throttle'
import { getGoodsLists, createOrder, getAddressLists,getGoodsInfo } from "@/api/purchaseOrder/purchase.js"
import { getGoodsCateLists } from "@/api/goods/goods"
import add from "../goods/handle/add0"
// import audit from "./handle/auditDetails"

export default {
    name: 'goods',
    components: {
        add,
        // audit
    },
    data() {
        return {
            showSearch: true,
            loading: false,
            total: 0,
            pageCount: 0,
            queryParams: {
                page: 1,
                limit: 20,
                key: '',
                key_cate_id:'',
            },
            tableList: [
                {}
            ],
            selectData: [],
            goodsList: [],
            selectList: [],
            GoodList: [],
            btnList: [
                {
                    dictLabel: '全部商品',
                    dictValue: ''
                },
                {
                    dictLabel: '已上架',
                    dictValue: 1
                },
                {
                    dictLabel: '未上架',
                    dictValue: -1
                },
                {
                    dictLabel: '待审核',
                    dictValue: 0
                },
                // {
                //     dictLabel: '未通过',
                //     dictValue: 4
                // },
            ],
            curLine: 0,
            handleShow: "",
            submitShow: null,
            title: "",
            statusShow: true,
            statusString: '',
            curRow: {},
            stockRow: {},
            formLoading: false,
            form: {

            },
            rules: {
                address_id: [{ required: true, message: '请选择收货地址', trigger: 'blur' }],
            },
            staffList: [],
            listCount: '',
            codeList: [],
            codes: '',
            addressList: [],
            cateList: [],
            cateIds: [],
            optionProps: {
                value: 'id',
                label: 'name',
                disabled: "disabled",
                children: 'children',
                emitPath: true,
            },
            resetCascader: 0,
            cate_ids:[],
        }
    },
    // watch: {
    //     'selectList.stock_sales'(val) {
    //         if (val) {
    //             for (let i = 0; i < this.selectList.length; i++) {
    //                 let goodsInfo =  this.selectList[i]
    //                 this.GoodList.push({
    //                     'goods_code':goodsInfo.code,
    //                     'goods_sku':goodsInfo.goods_sku,
    //                     'stock_sales':goodsInfo.stock_sales
    //                 })
    //             }
    //             console.log(this.GoodList, 888)
    //         }
    //     }
    // },
    created() {
        // setTimeout(() => {
        //             this.handleSelectedDataChange();
        //         }, 1000);// 测试过了，比三秒短的话，还是会报错
        this.getList();
        this.getCateList();
    },
    methods: {
        getList() {
            this.loading = true;
            console.log(this.selectData, 'chushi')
            getGoodsLists(this.queryParams).then(res => {
                // setTimeout(() => {
                //     this.handleSelectedDataChange();
                // }, 1000);// 测试过了，比三秒短的话，还是会报错
                this.tableList = res.data ? res.data.lists : [];
                this.pageCount = res.data.pageCount;
                this.listCount = res.data.listsCount;
                this.loading = false;
            });
        },
        getCateList(){
            getGoodsCateLists().then(res =>{
                this.cateList = res.data
            this.cateList.forEach(e => {
                if (e && e.children) {
                    e.disabled = false
                } else {
                    e.disabled = true
                }
            });
            })

        },
        handleChange(id, cate_ids){
            console.log(id, cate_ids, "id, cate_ids")
            this.queryParams.key_cate_id = cate_ids[1]
            this.getList();
        },
        getAddressList() {
            let params = {
                page: 1,
                limit: 100
            }
            getAddressLists(params).then(res => {
                this.addressList = res.data.lists;
            });
        },
        getRowKeys(row) {
            return row.index  // 指定table code
        },
        toggleSelection(row) {
            this.$refs.tableList.toggleRowSelection(row);
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.selectData = selection;
            console.log(this.selectData, "cccc0")
        },
        handleQuery() {
            this.queryParams.page = 1;
            this.getList();
        },
        resetQuery() {
            this.resetForm("queryForm");
            this.queryParams.key_cate_id = '',
            this.cate_ids = [],
            this.handleQuery();
        },
        toDetail(row) {
            getGoodsInfo({code : row.code }).then(res => {
                this.title = "详情"
                this.curRow = res.data;
                this.handleShow = 'detail';
            })
        },

        // selectData中的值发生变化时同步到选中项
        handleSelectedDataChange() {
            this.selectData.length && this.selectData.forEach((item) => {
                this.$nextTick(() => {
                    const row = this.tableList.find((i) => i.index === item.index);
                    console.log(row, 'row')
                    this.$refs.tableList.toggleRowSelection(row);
                })
            });
        },

        close() {
            this.curRow = {}
            this.form = {}
            this.handleShow = ""
            this.GoodList = []
            this.selectData = []
        },
        handleCreate() {
            if (this.selectData.length == 0) {
                this.$confirm('请选择商品进行操作', "警告", {
                    confirmButtonText: "确定",
                    type: "warning"
                })
            } else if (this.selectData.length > 0) {
                this.selectList = this.selectData
                console.log(this.selectList, 6666)
                for (let i = 0; i < this.selectList.length; i++) {
                    let goodsInfo = this.selectList[i]
                    // if (!goodsInfo.stock_sales) {
                    //     this.$message.error('请输入商品数量');
                    // } else{
                    this.GoodList.push({
                        'goods_code': goodsInfo.code,
                        'goods_sku': goodsInfo.goods_sku,
                        'stock_sales': goodsInfo.stock_sales ? goodsInfo.stock_sales : 1
                    })
                    console.log(this.GoodList, 888)
                    this.getAddressList()
                    this.handleShow = 'assign'
                    // let params = {
                    //     address_id: 2,
                    //     goods_json: JSON.stringify(this.GoodList)
                    // }
                    // this.$confirm('是否确认批量采购选中商品?', "警告", {
                    //     confirmButtonText: "确定",
                    //     cancelButtonText: "取消",
                    //     type: "warning"
                    // }).then(function () {
                    //     return createOrder(params);
                    // }).then(() => {
                    //     this.getList();
                    //     this.GoodList = []
                    //     this.selectData = []
                    //     console.log(this.GoodList, '000')
                    //     this.msgSuccess("操作成功");
                    // })
                    // }
                }
            }
        },
        handleCreate0(row){
            this.GoodList.push({
                        'goods_code': row.code,
                        'goods_sku': row.goods_sku,
                        'stock_sales': row.stock_sales ? row.stock_sales : 1
                    })
                    console.log(this.GoodList, 888)
                    this.getAddressList()
                    this.handleShow = 'assign'

        },
        submit: throttle(function () {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.formLoading = true;
                    let params = {
                        address_id: this.form.address_id,
                        goods_json: JSON.stringify(this.GoodList)
                    }
                    console.log(params,'params')
                    createOrder(params).then(res => {
                         this.$alert("提示",{
                            confirmButtonText:"确定",
                            message:res.info
                         })
                        // this.msgSuccess("操作成功！");
                        this.close()
                        this.formLoading = false;
                        this.$refs.tableList.clearSelection();
                        this.getList();
                    }).catch(() => {
                        this.formLoading = false;
                    })
                }
            })
        }, 1000, { trailing: false }),
    },
}

</script>
<style scoped lang='scss'></style>